import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';

class PublicImage extends StatelessWidget {
  String image;
  double width = 46.w;
  double height = 46.w;
  BoxFit fit = BoxFit.cover;
  String defaultImage = 'assets/images/dapp/empty_avatar.png';

  PublicImage(
      {super.key,
      required this.image,
      this.width = 46,
      this.height = 46,
      this.fit = BoxFit.cover,
      this.defaultImage = 'assets/images/dapp/empty_avatar.png'});

  @override
  Widget build(BuildContext context) {
    RegExp regex = RegExp("^http"); // 使用正则表达式 "^http" 匹配以 "http" 开头的字符串
    bool isStartsWithHttp = regex.hasMatch(image);
    bool isSvg = image.endsWith('.svg');
    if (isSvg) {
      return SvgPicture.network(
        image,
        width: width,
        height: height,
      );
    }
    if (isStartsWithHttp) {
      return CachedNetworkImage(
          fit: fit,
          imageUrl: image,
          placeholder: (context, url) => Image.asset(
                defaultImage,
                width: width,
                height: height,
              ),
          width: width,
          height: height,
          errorWidget: (context, url, error) => Image.asset(
                defaultImage,
                width: width,
                height: height,
                //设置图片在左边对齐
                alignment: Alignment.center,
              ));
    }
    // TODO: implement build
    return Image.asset(
      image,
      width: width,
      height: height,
      fit: fit,
      errorBuilder:
          (BuildContext context, Object exception, StackTrace? stackTrace) {
        return Image.asset(
          defaultImage,
          width: width,
          height: height,
          //设置图片在左边对齐
          alignment: Alignment.center,
        );
      },
    );
  }
}
